package com.shanzmoo.admin.manager.store;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.admin.domain.dto.StoreStockAllotBillCancelDTO;
import com.shanzmoo.admin.domain.dto.StoreStockAllotBillDetailSaveDTO;
import com.shanzmoo.admin.domain.dto.StoreStockAllotBillSaveDTO;
import com.shanzmoo.admin.domain.dto.StoreStockAllotBillUpdateDTO;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.e.SysBillTypeEnum;
import com.shanzmoo.base.exception.StoreException;
import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.core.manager.CodeManager;
import com.shanzmoo.db.store.entity.StoreStockAllotBillDetailEntity;
import com.shanzmoo.db.store.entity.StoreStockAllotBillEntity;
import com.shanzmoo.db.store.entity.query.StoreStockAllotBillQuery;
import com.shanzmoo.db.store.entity.vo.StoreStockAllotBillDetailVO;
import com.shanzmoo.db.store.entity.vo.StoreStockAllotBillVO;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.db.store.service.IStoreStockAllotBillDetailService;
import com.shanzmoo.db.store.service.IStoreStockAllotBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 仓库调拨单 管理器
 *
 * @author Gzhao 2021-03-11
 */
@Slf4j
@Component
public class StoreStockAllotBillManager {

    @Autowired
    private IStoreStockAllotBillService storeStockAllotBillService;

    @Autowired
    private IStoreStockAllotBillDetailService storeStockAllotBillDetailService;

    @Autowired
    private CodeManager codeManager;

    /**
     * 分页查询
     */
    public PageRespBase<StoreStockAllotBillVO> queryPage(StoreStockAllotBillQuery query) {
        Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<StoreStockAllotBillVO> reList = storeStockAllotBillService.queryPageList(query);

        if (CollUtil.isNotEmpty(reList)) {
            List<Integer> billIds = reList.stream().map(StoreStockAllotBillVO::getId).collect(Collectors.toList());
            List<StoreStockAllotBillDetailVO> detailAllList = storeStockAllotBillDetailService.queryListByIds(billIds);

            for (StoreStockAllotBillVO billVO : reList) {
                List<StoreStockAllotBillDetailVO> detailList = detailAllList.stream()
                        .filter(e -> e.getBillId().equals(billVO.getId()))
                        .collect(Collectors.toList());
                billVO.setDetailList(detailList);
            }
        }

        PageRespBase<StoreStockAllotBillVO> result = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return result;
    }

    /**
     * 作废调拨单
     * @param cancelDTO
     * @return
     */
    public SResponse<Boolean> cancel(StoreStockAllotBillCancelDTO cancelDTO) {
        /**
         * todo 取消调拨单
         * 1. 验证调拨单状态
         * 2. 更新调拨单作废信息
         */
        beforeOperation(cancelDTO.getId());
        StoreStockAllotBillEntity storeStockAllotBillEntity = cancelDTO.convertEntity();
        storeStockAllotBillEntity.setStatus(9);
        storeStockAllotBillService.updateById(storeStockAllotBillEntity);
        return SResponse.ok();
    }

    private void beforeOperation(Integer id) {
        StoreStockAllotBillEntity checkEntity = storeStockAllotBillService.getById(id);
        if(checkEntity.getStatus() != 0){
            throw new StoreException("调拨单状态为待审核时才能进行状态操作!");
        }
    }

    /**
     * 调拨单审核
     * @param billId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SResponse<Boolean> examine(Integer billId) {
        /**
         * todo 调拨单审核
         * 1. 验证调拨单状态
         * 2. 更新调拨单审核状态
         * 3. 修改实时库存，写入库存流水
         * 4. 若调拨的商品属于用户，同时更新用户库存
         */
        // 验证调拨单状态
        beforeOperation(billId);
        // 更新调拨单审核状态
        StoreStockAllotBillEntity updateEntity = new StoreStockAllotBillEntity();
        updateEntity.setId(billId);
        updateEntity.setStatus(1);
        updateEntity.setExamineUser(CurrentUserCache.getUserId());
        updateEntity.setExamineTime(LocalDateTime.now());
        storeStockAllotBillService.updateById(updateEntity);
        // todo 修改实时库存，写入库存流水
        List<StoreStockAllotBillDetailVO> listByBillId = storeStockAllotBillDetailService.getListByBillId(billId);




        return SResponse.ok();
    }

    /**
     *
     *
     * @author Gzhao 2021/3/11
     * @param id 仓库调拨单id
     * @return
     */
    public SResponse<StoreStockAllotBillVO> getInfo(Integer id) {
        StoreStockAllotBillVO rsVO = storeStockAllotBillService.getInfo(id);
        List<StoreStockAllotBillDetailVO> detailList = storeStockAllotBillDetailService.getListByBillId(id);
        rsVO.setDetailList(detailList);
        return SResponse.ok(rsVO);
    }

    /**
     * 保存调拨单
     * @param saveDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveAllotBill(StoreStockAllotBillSaveDTO saveDto) {
        StoreStockAllotBillEntity storeStockAllotBillEntity = saveDto.convertEntity();
        if(storeStockAllotBillEntity.getId() == null){
            storeStockAllotBillEntity.setBillNo(codeManager.generateBillNo(SysBillTypeEnum.ALLOT_BILL));
            storeStockAllotBillEntity.setCreateUser(CurrentUserCache.getUserId());
        }else{
            //修改判断状态
            beforeOperation(storeStockAllotBillEntity.getId());
        }
        storeStockAllotBillService.saveOrUpdate(storeStockAllotBillEntity);
        //如编辑,先删除原有
        List<StoreStockAllotBillDetailEntity> oldDetails = storeStockAllotBillDetailService.list(Wrappers.<StoreStockAllotBillDetailEntity>lambdaQuery()
                .eq(StoreStockAllotBillDetailEntity::getBillId,storeStockAllotBillEntity.getId())
                .eq(StoreStockAllotBillDetailEntity::getDeleted,Boolean.FALSE));
        if(CollUtil.isNotEmpty(oldDetails)){
            oldDetails.stream().forEach(r -> {
                r.setDeleted(true);
            });
            storeStockAllotBillDetailService.updateBatchById(oldDetails);
        }
        //插入
        List<StoreStockAllotBillDetailSaveDTO> detailList = saveDto.getDetailList();
        List<StoreStockAllotBillDetailEntity> rsList = detailList.stream()
                .map(StoreStockAllotBillDetailSaveDTO::convertEntity)
                .collect(Collectors.toList());
        rsList.stream().forEach(r -> {
            r.setBillId(storeStockAllotBillEntity.getId());
        });
        storeStockAllotBillDetailService.saveBatch(rsList);

    }

    /**
     * 修改调拨单
     * @param updateDto
     */
    public void updateAllotBill(StoreStockAllotBillUpdateDTO updateDto) {
    }
}
